<?php
/**
 +----------------------------------------------------------------------------------------------------
 * 核心函数库
 +----------------------------------------------------------------------------------------------------
 */
define( 'CORE_FUNCTION', TRUE ) ;

/**
 * 获取客户端IP地址
 * @return	String 返回客户端的ip
 */
function _get_client_ip() {
	$clientip = '' ;
	if ( getenv( 'HTTP_CLIENT_IP' ) && strcasecmp( getenv( 'HTTP_CLIENT_IP' ), 'unknown' ) ) {
		$clientip = getenv( 'HTTP_CLIENT_IP' ) ;
	} elseif ( getenv( 'HTTP_X_FORWARDED_FOR' ) && strcasecmp( getenv( 'HTTP_X_FORWARDED_FOR' ), 'unknown' ) ) {
		$clientip = getenv( 'HTTP_X_FORWARDED_FOR' ) ;
	} elseif ( getenv( 'REMOTE_ADDR' ) && strcasecmp( getenv( 'REMOTE_ADDR' ), 'unknown' ) ) {
		$clientip = getenv( 'REMOTE_ADDR' ) ;
	} elseif ( isset( $_SERVER['REMOTE_ADDR'] ) && $_SERVER['REMOTE_ADDR'] && strcasecmp( $_SERVER['REMOTE_ADDR'], 'unknown' ) ) {
		$clientip = $_SERVER['REMOTE_ADDR'] ;
	}
	preg_match( "/[\d\.]{7,15}/", $clientip, $clientipmatches ) ;
	$clientip = $clientipmatches[0] ? $clientipmatches[0] : 'unknown' ;
	return $clientip ;
}

/**
 +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 +----------------------------------------------------------
 * @static
 * @access public
 +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $suffix 截断显示字符
 * @param string $charset 编码格式
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function msubstr( $str, $start = 0, $length, $suffix = false, $splitItem = '...',$charset = "utf-8") {
	if ( function_exists( "mb_substr" ) ){
		$_str = mb_substr( $str, $start, $length, $charset) ;
		if($suffix){
			if( mb_strlen($str,$charset) > $length ){
				$_str .= $splitItem;
			}
		}
		return $_str;
	}elseif ( function_exists( 'iconv_substr' ) ) {
		$_str = iconv_substr( $str, $start, $length, $charset) ;
		if($suffix){
			if( iconv_strlen($str,$charset) > $length ){
					$_str .= $splitItem;
			}
		}
		return $_str;
	}
	$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/" ;
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/" ;
	$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/" ;
	$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/" ;
	preg_match_all( $re[$charset], $str, $match ) ;
	$slice = join( "", array_slice( $match[0], $start, $length ) ) ;
	if ( $suffix )
		return $slice . $splitItem;
	return $slice ;
}

function implode_field_value( $array, $glue = ',' ) {
	$sql = $comma = '' ;
	foreach ( $array as $k => $v ) {
		$sql .= $comma . "`$k`='$v'" ;
		$comma = $glue ;
	}
	return $sql ;
}

///**
// * 通过UID获取用户数据;
// * @param	INT		$uid	用户ID;
// * @return	ARRAY	返回用户相关信息;
// */
//function _get_user_byID( $uid ) {
//	static $users = array() ;
//	if ( empty( $users[$uid] ) ) {
//		$users[$uid] = D( 'Member' , 'member' )->getby_uid( $uid ) ;
//	}
//	return $users[$uid] ;
//}
/**
 * 批量转义
 * @param	String or ARRAY	要转义的字符 或者数组
 * @return	String or ARRAY	返回一个处理后的数组串或数组
 */
function haddslashes( $string ) {
	if ( is_array( $string ) ) {
		foreach ( $string as $key => $val ) {
			unset( $string[$key] ) ;
			$string[addslashes( $key )] = haddslashes( $val ) ;
		}
	} else {
		$string = addslashes( $string ) ;
	}
	return $string ;
}

/**
 * 批量反转义
 * @param	String or ARRAY 要反转义的字符串或者数组
 * @return	String or ARRAY	返回一个处理后的数组串或数组
 */
function hstripslashes( $string ) {
	if ( is_array( $string ) ) {
		foreach ( $string as $key => $val ) {
			$string[$key] = hstripslashes( $val ) ;
		}
	} else {
		$string = stripslashes( $string ) ;
	}
	return $string ;
}

/**
 * 随机函数,返回随机字符串
 * @param Int	$length		随机字符串的长度
 * @param Bool	$numeric	选择启用10进制或35进制随机数. false=35进制,true=10进制	
 * @return String 			随机字符串
 */
function random( $length, $numeric = 0 ) {
	$seed = base_convert( md5( microtime() . $_SERVER['DOCUMENT_ROOT'] ), 16, $numeric ? 10 : 35 ) ;
	$seed = $numeric ? (str_replace( '0', '', $seed ) . '012340567890') : ($seed . 'zZ' . strtoupper( $seed )) ;
	$hash = '' ;
	$max = strlen( $seed ) - 1 ;
	for ( $i = 0; $i < $length; $i ++ ) {
		$hash .= $seed{mt_rand( 0, $max )} ;
	}
	return $hash ;
}

/**
 * 加密算法
 * @param	STRING	$string		要处理的字符串
 * @param	STRING	$operation	处理方式		1、ENCODE 2、DECODE
 * @param	STRING	$key		密钥			此处默认读取配置文件
 * @return	STRING	经过处理后的字符串
 */
function authCode( $string, $operation = 'DECODE', $key = '' ) {
	$ckey_length = 4 ;
	$key = md5( $key != '' ? $key : C( 'authkey' ) ) ;
	$keya = md5( substr( $key, 0, 16 ) ) ;
	$keyb = md5( substr( $key, 16, 16 ) ) ;
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr( $string, 0, $ckey_length ) : substr( md5( microtime() ), -$ckey_length )) : '' ;
	$cryptkey = $keya . md5( $keya . $keyc ) ;
	$key_length = strlen( $cryptkey ) ;
	$string = $operation == 'DECODE' ? base64_decode( substr( $string, $ckey_length ) ) : sprintf( '%010d', $expiry ? $expiry + time() : 0 ) . substr( md5( $string . $keyb ), 0, 16 ) . $string ;
	$string_length = strlen( $string ) ;
	$result = '' ;
	$box = range( 0, 255 ) ;
	$rndkey = array() ;
	for ( $i = 0; $i <= 255; $i ++ ) {
		$rndkey[$i] = ord( $cryptkey[$i % $key_length] ) ;
	}
	for ( $j = $i = 0; $i < 256; $i ++ ) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256 ;
		$tmp = $box[$i] ;
		$box[$i] = $box[$j] ;
		$box[$j] = $tmp ;
	}
	for ( $a = $j = $i = 0; $i < $string_length; $i ++ ) {
		$a = ($a + 1) % 256 ;
		$j = ($j + $box[$a]) % 256 ;
		$tmp = $box[$a] ;
		$box[$a] = $box[$j] ;
		$box[$j] = $tmp ;
		$result .= chr( ord( $string[$i] ) ^ ($box[($box[$a] + $box[$j]) % 256]) ) ;
	}
	if ( $operation == 'DECODE' ) {
		if ( (substr( $result, 0, 10 ) == 0 || substr( $result, 0, 10 ) - time() > 0) && substr( $result, 10, 16 ) == substr( md5( substr( $result, 26 ) . $keyb ), 0, 16 ) ) {
			return substr( $result, 26 ) ;
		} else {
			return '' ;
		}
	} else {
		return $keyc . str_replace( '=', '', base64_encode( $result ) ) ;
	}
}

/**
 * 返回头像
 * @param String	$uid		用户ID
 * @param String	$size		头像尺寸 /Big/middle/small
 * @param Bool		$returnsrc	返回URL或HTML标签. FALSE为返回URL,TRUE为返回标签; 默认FALSE
 * @param Bool		$real		返回实际尺寸. 为TRUE时返回实际尺寸; 默认为FALSE
 * @param String	$ucenterurl	ucenter路径,默认为空;(从配置文件读取)
 */
function avatar( $uid, $size = 'middle', $returnsrc = FALSE, $real = FALSE, $ucenterurl = '' ) {
	loaducenter() ;
	$ucenterurl = empty( $ucenterurl ) ? UC_API : $ucenterurl ;
	$size = in_array( $size, array( 
		'big' , 
		'middle' , 
		'small' 
	) ) ? $size : 'middle' ;
	$uid = abs( intval( $uid ) ) ;
	return $returnsrc ? $ucenterurl . '/avatar.php?uid=' . $uid . '&size=' . $size : '<img src="' . $ucenterurl . '/avatar.php?uid=' . $uid . '&size=' . $size . ($real ? '&type=real' : '') . '" />' ;
}

function loaducenter() {
	# hooks #
	require_cache( PLUGIN_PATH . '/Ucenter/config.inc.php' ) ;
	require_cache( PLUGIN_PATH . '/Ucenter/uc_client/client.php' ) ;
}


function update_cookie( & $userinfo ) {
	Director::Instance( $userinfo, 'Cookie', 'Set', 'None' ) ;
}
function update_session( & $userinfo ) {
	Director::Instance( $userinfo, 'Session', 'Set', 'Array' ) ;
}

/*
 * @desc  更新积分数;
 * @param $title    显示标题;
 * @param $uid      用户ID;
 * @param $pk       关联主键ID;
 * @param $pk_type  关联主键类型[1,视频; 2,专题; 3,空间; 4,活动];
 * @param $credit   积分;
 * @param $type     类型[1,登录,2,评论,3,观看,4,兑换,7,问对,8,回答,10,抽奖,99其他];
 * @param $dateline 时间[日期];
 * @param $num      每天允许的数量;
 * @param $opt      操作类型[1,加; 0,减]
 * @param $act      活动关联
 */
function update_credit($title, $uid, $pk = 0, $type = 1, $pk_type = 0, $num = 1, $dateline = 0, $credit = 1 , $opt = 1, $act = 0){
	if($dateline === 0){
		$dateline = date('Y-m-d');
	}
	$rs = M('common_creditlog');
	$handler = M('common_member');
	$data = $where = array();
	# 检测是超过指定次数;
	$where['log_date'] = $dateline;
	$where['log_to_type'] = $pk_type;
	$where['log_type'] = $type;
	$where['log_uid'] = $uid;
	if($pk != 0){
		if($rs->where( array_merge( $where, array('log_to_pk'=> $pk) ) )->count() ){
			return false;
		}
	}
	$_count = $rs->where($where)->count();
	if($_count < $num){
		# 积分动态;
		$func = $opt == 1 ? 'setInc' : 'setDec';
		$FIELD = 'credits';
		if(defined('CREDIT_ACTIVITY')){
			$FIELD = 'accredits';
		}
		$handler->$func( $FIELD , "uid={$uid}", $credit );
		# Log记录;
		$data['log_uid'] = $uid;
		$data['log_title'] = $title;
		$data['log_credit'] = $credit;
		$data['log_addtime'] = time();
		$data['log_to_pk'] = $pk;
		$data['log_to_type'] = $pk_type;
		$data['log_date'] = $dateline;
		$data['log_type'] = $type;
		$data['log_opt'] = $opt;
		$data['log_act'] = $act;
		$rs->add($data);
		return true;
	}
	return false;
}


function list_to_tree( $list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0 ) {
	// 创建Tree
	$tree = array() ;
	if ( is_array( $list ) ) {
		// 创建基于主键的数组引用
		$refer = array() ;
		foreach ( $list as $key => $data ) {
			$refer[$data[$pk]] = & $list[$key] ;
		}
		foreach ( $list as $key => $data ) {
			// 判断是否存在parent
			$parentId = $data[$pid] ;
			if ( $root == $parentId ) {
				$tree[] = & $list[$key] ;
			} else {
				if ( isset( $refer[$parentId] ) ) {
					$parent = & $refer[$parentId] ;
					$parent[$child][] = & $list[$key] ;
				}
			}
		}
	}
	return $tree ;
}

/**
 +----------------------------------------------------------
 * 对查询结果集进行排序
 +----------------------------------------------------------
 */
function list_sort_by( $list, $field, $sortby = 'asc' ) {
	if ( is_array( $list ) ) {
		$refer = $resultSet = array() ;
		foreach ( $list as $i => $data )
			$refer[$i] = &$data[$field] ;
		switch ( $sortby ) {
			case 'asc' : // 正向排序
				asort( $refer ) ;
				break ;
			case 'desc' : // 逆向排序
				arsort( $refer ) ;
				break ;
			case 'nat' : // 自然排序
				natcasesort( $refer ) ;
				break ;
		}
		foreach ( $refer as $key => $val )
			$resultSet[] = &$list[$key] ;
		return $resultSet ;
	}
	return false ;
}

/**
 +----------------------------------------------------------
 * 在数据列表中搜索
 +----------------------------------------------------------
 */
function list_search( $list, $condition ) {
	if ( is_string( $condition ) )
		parse_str( $condition, $condition ) ;
		// 返回的结果集合
	$resultSet = array() ;
	foreach ( $list as $key => $data ) {
		$find = false ;
		foreach ( $condition as $field => $value ) {
			if ( isset( $data[$field] ) ) {
				if ( 0 === strpos( $value, '/' ) ) {
					$find = preg_match( $value, $data[$field] ) ;
				} elseif ( $data[$field] == $value ) {
					$find = true ;
				}
			}
		}
		if ( $find )
			$resultSet[] = &$list[$key] ;
	}
	return $resultSet ;
}
